<template>
  <div class="merchandise-management views-container">
    <div class="wlm-table">

    <el-form
      ref="form"
      :model="formFormatData.formData"
      :rules="formFormatData.rules"
      label-width="100px"
    >
      <el-form-item label="商品封面"  ref="evaluation" >
        <div class="" v-if="showInput" >
             <el-image v-if="formFormatData.formData.cover_img_url.length>0"
      style="width: 100px; height: 100px"
      :src="formFormatData.formData.cover_img_url[0].file_path"
      ></el-image>
        </div>
       <div class="" v-else>
          <choose-files
          ref="chooseFiles"
          :config="chooseCoverConfig"
          :changeEvt="formFormatFiltersChange"
        ></choose-files>
        <div class="form-help">建议尺寸：300×300</div>
        <div class="form-help">图片大小不得超过3M</div>
       </div>
      </el-form-item>

      <el-form-item  label="商品标题">
        <el-input :disabled="showInput"  v-model="formFormatData.formData.name" style="width:520px"></el-input>
        <div class="">最长14个汉字，1个汉字相当于2个字符</div>
      </el-form-item>
       <el-form-item label="排序">
        <el-input-number v-model="formFormatData.formData.goods_sort"  :min="1" :max="9999" label="描述文字"></el-input-number>
        <div class="">请输入数字</div>
      </el-form-item>

      <el-form-item label="价格形式">
        <el-radio-group v-model="formFormatData.formData.price_type" style="float: left">
          <div class="priceRadio">
            <el-radio :label="1">一口价</el-radio>
          </div>
          <div class="priceRadio">
            <el-radio :label="2">价格区间</el-radio>
          </div>
          <div class="priceRadio">
            <el-radio :label="3">显示折扣价</el-radio>
          </div>
        </el-radio-group>

        <div class="priceTabel">
          <div class>
            <span>价格</span>
            <el-input v-model="fixedPrice" style="width:120px" size="mini">
              <template slot="append">元</template>
            </el-input>
          </div>
          <div class>
            <span>价格</span>
            <el-input v-model="minPrice" style="width:120px" size="mini">
              <template slot="append">元</template>
            </el-input>
            <span>至</span>
            <el-input v-model="maxPrice" style="width:120px" size="mini">
              <template slot="append">元</template>
            </el-input>
          </div>
          <div class>
            <span>原价</span>
            <el-input v-model="oldPrice" style="width:120px" size="mini">
              <template slot="append">元</template>
            </el-input>
            <span>现价</span>
            <el-input v-model="newPrice" style="width:120px" size="mini">
              <template slot="append">元</template>
            </el-input>
          </div>
        </div>
      </el-form-item>
       <el-form-item label="添加分销商">
                                <chooseUser :config="addInitChooseUser" ref="chooseUser" :changeEvt="mainUserChange" v-if="!showInput">
                                </chooseUser>
                                 <el-tag v-if="dealer_name!=''" type="success">{{dealer_name}}</el-tag>
                            </el-form-item>

      <el-form-item label="商品链接">
        <choose-goods ref="chooseGoods" :config="chooseGoodsConfig" :changeEvt="filtersChange" ></choose-goods>
        <el-button type="primary" @click="goodsToogle" v-if="!showInput">选择商品</el-button>
          <!-- <el-tag v-if="goodsName!=''" type="success">{{goodsName}}</el-tag> -->
        <el-table v-if="formFormatData.formData.goods!=''" :data="formFormatData.formData.goods" style="width: 20%;margin-top:20px">
          <el-table-column prop="date" label="商品">
            <template slot-scope="scope">
              <div class="flex-row">
                <img class="logo" v-if="scope.row.image " :src="scope.row.image[0]['file_path']" />
                <div class="inner-text">
                  <p>{{scope.row.goods_name}}</p>
                  <!-- <p>￥{{scope.row.sku[0].goods_price}}</p> -->
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="date" label="库存">
            <template slot-scope="scope">
              <p>{{scope.row.stock}}</p>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="operation-group">
                <el-button class="wlm-text" type="text" @click="deleteTable(scope)">删除</el-button>
              </div>
            </template>
          </el-table-column> -->
        </el-table>
      </el-form-item>

      <div class style="text-align: center;">
        <img :src="goodsQR"  style="width:200px">
        <p>校验成功，可用微信扫码预览商品</p>
      </div>
      <el-form-item class="saveBtn">
        <div class="" v-if="showInput">
            <el-button @click="gengxin" :loading="loading"  type="primary">更新</el-button>
         </div>
       <div class="" v-else>

          <el-button @click="onSubmit(2)" :loading="loading">保存</el-button>
        <el-button type="primary" @click="onSubmit(1)" :loading="loading">保存并审核</el-button>
       </div>
      </el-form-item>
    </el-form>
    </div>
  </div>
</template>
<script>
import mixins from '@/mixins/mixins'
import ChooseGoods from '@/components/ChooseGoods/index'
import ChooseFiles from '@/components/ChooseFiles/index'
import ChooseUser from '@/components/ChooseUser/chooseDistrbutor'
import {
  distributorUser

} from '@/api/distribution'
import { addLiveGoods, getGoodsPreviewCode, getLiveGoodsInfo } from '@/api/setting'
import {updateLiveGoods} from '@/api/upload'
// import { CLIENT_RENEG_WINDOW } from 'tls'
export default {
  mixins: [mixins.getters('Form')],
  mounted() {
    console.log(this.$route.query.id)
    if (this.$route.query.id) {
      this.compile = true
      getLiveGoodsInfo({ id: this.$route.query.id }).then(res => {
        const data = res.data.data;

        if (data.price_type == 1) {
          this.fixedPrice = data.price
        } else if (data.price_type == 2) {
          this.minPrice = data.price
          this.maxPrice = data.price2
        } else if (data.price_type == 3) {
          this.oldPrice = data.price
          this.newPrice = data.price2
        }
        // this.goodsName = data.name;
        this.dealer_name = data.dealer_name;
         if(data.audit_status==2){
          this.showInput=true;
        }
        // this.formFormatData.formData.goods_id = data.goods_id
      })
    };

  },
  data() {
    return {
      formFormatData: {
        key: 'userForm',
        api: {
          editForm: {
            api: getLiveGoodsInfo,
            params: {
              id: ''
            },
            redirect: 'id',
            filters: {
              img: {
                bindInit: ['chooseCoverConfig']
              },
              choose: {
                bindInit: ['chooseGoodsConfig']
              }
            }

          },
          submitForm: addLiveGoods
        },
        formData: {
          goods: [],
          cover_img_url: [],
          name: '',
          price_type: 1,
          price: 1,
          price2: null,
          goods_id: '',
          type: 1,
          goods_sort: 999,
          dealer_id: '',
          audit_status:null

        },
        rules: {
          name: [
            { required: true, message: '请输入标签名称', trigger: 'blur' }
          ]
        }
      },
      addInitChooseUser: {
        closable: true,
        initList: [],
        requestApi: distributorUser
      },
      chooseGoodsConfig: {
        type: ['chooseGoods'],
        model: 'normal',
        unique: true,
        initList: [],

      },
      isAdd: false,
      showInput:false,
      loading: false,
      goodsName: '',
      dealer_name: '',
      goods: [],
      goodsQR: '',
      compile: false,
      fixedPrice: 1,
      minPrice: 1,
      maxPrice: 1,
      oldPrice: 1,
      newPrice: 1,
      dialogImageUrl: '',
      dialogVisible: false,
      chooseCoverConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          isMore: true,
          isLocal: true,
          model: 'display'
        },
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'cover_img_url',
          model: 'img',
          validateField: ''
        }
      }
    }
  },
  components: {
    ChooseGoods,
    ChooseFiles,
    ChooseUser
  },
  methods: {
    mainUserChange(distributorUser) {
      this.dealer_name = ''
      console.log(distributorUser)
      const [item] = distributorUser
      if (item) {
        this.formFormatData.formData.dealer_id = item.user_id
      } else {
        this.formFormatData.formData.dealer_id = 0
      }
    },
    filtersChange(val) {

      this.formFormatData.formData.goods = val.displayData

      this.goodsName = ''
      getGoodsPreviewCode({ goods_id: this.formFormatData.formData.goods[0].goods_id }).then(res => {
        console.log(res, '二维码图片地址')
        this.goodsQR = res.data.data.code_url
      })
    },

    deleteTable(scope) {
      this.goods = []
    },
    gengxin(){
      this.loading=true;
      switch (this.formFormatData.formData.price_type) {
        case 1:
          this.formFormatData.formData.price = parseFloat(this.fixedPrice)
          this.formFormatData.formData.price2 = 0

          break
        case 2:
          if (this.maxPrice <= this.minPrice) {
            this.$message.error('输入金额格式不正确！')
            return
          }
          this.formFormatData.formData.price = parseFloat(this.minPrice)
          this.formFormatData.formData.price2 = parseFloat(this.maxPrice)
          break
        case 3:
          this.formFormatData.formData.price = parseFloat(this.oldPrice)
          this.formFormatData.formData.price2 = parseFloat(this.newPrice)
          break
      }
        updateLiveGoods(this.formFormatData.formData).then(res=>{
          console.log(res)
          this.loading=false
               if(res.data.code==1){
                 thisrouter.push("/livetelecast/livegoods")
               }
        }).catch(rej=>{
          this.loading=false
        })
    },
    onSubmit(val) {
      switch (this.formFormatData.formData.price_type) {
        case 1:
          this.formFormatData.formData.price = this.fixedPrice
          this.formFormatData.formData.price2 = 0

          break
        case 2:
          if (this.maxPrice <= this.minPrice) {
            this.$message.error('输入金额格式不正确！')
            return
          }
          this.formFormatData.formData.price = this.minPrice
          this.formFormatData.formData.price2 = this.maxPrice
          break
        case 3:
          this.formFormatData.formData.price = this.oldPrice
          this.formFormatData.formData.price2 = this.newPrice
          break
      }
      if (this.formFormatData.formData.cover_img_url.length == 0) {
        this.$message.error('请上传商品图！')
        return
      }
      if (this.formFormatData.formData.name == '') {
        this.$message.error('请输入商品标题！')
        return
      }

      // if (this.formFormatData.formData.cover_img_url instanceof Array) {
      //   if (this.formFormatData.formData.cover_img_url.length > 0) {
      //     this.formFormatData.formData.cover_img_url = this.formFormatData.formData.cover_img_url[0].file_path
      //   }
      // }
      console.log(this.goods)
      if (this.goods.length > 0) {
        this.formFormatData.formData.goods_id = this.goods[0].goods_id
      }
      this.formFormatData.formData.type = val
      // if (this.formFormatData.formData.goods_id == '') {
      //   this.$message.error('请选择商品！')
      //   return
      // }
      this.loading = true
      this.formFormatSubmit({
        router: { type: 'replace', path: '/livetelecast/livegoods', code: 1 }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    goodsToogle() {
      console.log('amg')
      const result = []
      this.formFormatData.formData.goods.map((item) => {
        result.push(item.goods_id)
      })

      this.$refs.chooseGoods.currentRow = result
      this.$refs.chooseGoods.toggle()
    }
  }
}
</script>
<style lang="scss" scoped>
.priceRadio {
  margin-top: 16px;
}
.priceTabel {
  float: left;
  margin-left: 50px;
}
.saveBtn {
  margin-top: 50px;
  text-align: center;
}
</style>
